package com.jdrx.sw.sewage.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jdrx.sw.sewage.common.constant.Constant;
import com.jdrx.sw.sewage.common.helper.HttpUtils;
import com.jdrx.sw.sewage.service.common.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class HKServiceImpl {

    public static final Logger logger = LoggerFactory.getLogger(HKServiceImpl.class);
    String appKey = "d97364adf5344ef883a73362cdcb62f7";
    String appSecret = "08710993906881b8adabefdaa0d054ca";
    String host = "https://open.ys7.com";

    @Autowired
    private RedisService redisService;

    public String getAccessToken(String tenantId) throws Exception {
        String cacheAccessToken = redisService.getStr(Constant.HK_ACCESS_TOKEN_KEY + tenantId);
        if (StringUtils.isNotEmpty(cacheAccessToken)) return cacheAccessToken;

        Map<String, String> bodys = Maps.newHashMap();
        bodys.put("appKey", appKey);
        bodys.put("appSecret", appSecret);
        JSONObject jsonObject = HttpUtils.doPost(host, "/api/lapp/token/get", Maps.newHashMap(), null, bodys);
        JSONObject data = jsonObject.getJSONObject("data");
        String accessToken = data.getString("accessToken");

        redisService.set(Constant.HK_ACCESS_TOKEN_KEY + tenantId, accessToken, 604740l);
        return accessToken;
    }

    public JSONObject getCameraListByPage(Integer pageStart, Integer pageSize, String tenantId) throws Exception {
        Map<String, String> bodys = Maps.newHashMap();
        bodys.put("accessToken", getAccessToken(tenantId));
        bodys.put("pageStart", pageStart.toString());
        JSONObject jsonObject = HttpUtils.doPost(host, "/api/lapp/camera/list", Maps.newHashMap(), null, bodys);
        return jsonObject;
    }

    public JSONArray getStreamUrl(String deviceSerial, Integer channelNo, String tenantId) throws Exception {
        Map<String, String> bodys = Maps.newHashMap();
        bodys.put("accessToken", getAccessToken(tenantId));
        bodys.put("source", deviceSerial + ":" + channelNo);

        JSONObject jsonObject = HttpUtils.doPost(host, "/api/lapp/live/address/get", Maps.newHashMap(), null, bodys);
        String code = jsonObject.getString("code");
        if (!"200".equals(code)) {
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject.get("msg"));
            return jsonArray;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        return data;
    }
}
